module Network.PGI.Handlers where

import Network.PGI
import TNET

constHandler :: (TNET a) => a -> Handler
constHandler v = const (return tv)
  where tv = toTNET v

constHandlerM :: (TNET a) => IO a -> Handler
constHandlerM iv = const (iv >>= return . toTNET)

makeHandler :: (TNET a, TNET b) => (a -> b) -> Handler
makeHandler f raw_req =
  case fromTNET raw_req of
    Nothing -> decodeError raw_req
    Just req -> return . toTNET $ f req

makeHandlerM :: (TNET a, TNET b) => (a -> IO b) -> Handler
makeHandlerM f raw_req =
  case fromTNET raw_req of
    Nothing -> decodeError raw_req
    Just req -> f req >>= return . toTNET

bodyData :: (TNET a) => a -> TValue
bodyData v = dict [ "body_data" .= v ]

decodeError tval = error $ unlines [ "Request was not the right type: "
                                   , (show . encode) tval
                                   ]
